const { EvaluationRecord, GameRecord, DailyRecord } = require('./model');
const { Op } = require('sequelize');

class EvaluationDao {
  // 创建评测记录
  async createEvaluationRecord(recordData) {
    try {
      return await EvaluationRecord.create(recordData);
    } catch (error) {
      throw new Error(`创建评测记录失败: ${error.message}`);
    }
  }

  // 根据ID查找评测记录
  async findEvaluationById(id) {
    try {
      return await EvaluationRecord.findByPk(id);
    } catch (error) {
      throw new Error(`查找评测记录失败: ${error.message}`);
    }
  }

  // 获取用户评测记录列表
  async getUserEvaluationRecords(userId, page = 1, limit = 10) {
    try {
      const offset = (page - 1) * limit;
      
      const { count, rows } = await EvaluationRecord.findAndCountAll({
        where: { user_id: userId },
        order: [['created_at', 'DESC']],
        limit,
        offset
      });

      return {
        total: count,
        list: rows,
        page,
        limit
      };
    } catch (error) {
      throw new Error(`获取评测记录失败: ${error.message}`);
    }
  }

  // 创建游戏记录
  async createGameRecord(recordData) {
    try {
      return await GameRecord.create(recordData);
    } catch (error) {
      throw new Error(`创建游戏记录失败: ${error.message}`);
    }
  }

  // 根据ID查找游戏记录
  async findGameById(id) {
    try {
      return await GameRecord.findByPk(id);
    } catch (error) {
      throw new Error(`查找游戏记录失败: ${error.message}`);
    }
  }

  // 获取用户游戏记录列表
  async getUserGameRecords(userId, page = 1, limit = 10) {
    try {
      const offset = (page - 1) * limit;
      
      const { count, rows } = await GameRecord.findAndCountAll({
        where: { user_id: userId },
        order: [['created_at', 'DESC']],
        limit,
        offset
      });

      return {
        total: count,
        list: rows,
        page,
        limit
      };
    } catch (error) {
      throw new Error(`获取游戏记录失败: ${error.message}`);
    }
  }

  // 创建每日记录
  async createDailyRecord(recordData) {
    try {
      return await DailyRecord.create(recordData);
    } catch (error) {
      throw new Error(`创建每日记录失败: ${error.message}`);
    }
  }

  // 根据ID查找每日记录
  async findDailyById(id) {
    try {
      return await DailyRecord.findByPk(id);
    } catch (error) {
      throw new Error(`查找每日记录失败: ${error.message}`);
    }
  }

  // 获取用户每日记录列表
  async getUserDailyRecords(userId, page = 1, limit = 10) {
    try {
      const offset = (page - 1) * limit;
      
      const { count, rows } = await DailyRecord.findAndCountAll({
        where: { user_id: userId },
        order: [['date', 'DESC']],
        limit,
        offset
      });

      return {
        total: count,
        list: rows,
        page,
        limit
      };
    } catch (error) {
      throw new Error(`获取每日记录失败: ${error.message}`);
    }
  }

  // 检查用户今日是否已朗读
  async checkTodayDailyRecord(userId) {
    try {
      const today = new Date().toISOString().split('T')[0];
      return await DailyRecord.findOne({
        where: {
          user_id: userId,
          date: today
        }
      });
    } catch (error) {
      throw new Error(`检查每日记录失败: ${error.message}`);
    }
  }

  // 获取用户统计数据
  async getUserStatistics(userId) {
    try {
      const evaluationCount = await EvaluationRecord.count({
        where: { user_id: userId }
      });

      const gameCount = await GameRecord.count({
        where: { user_id: userId }
      });

      const dailyCount = await DailyRecord.count({
        where: { user_id: userId }
      });

      // 计算平均分数
      const evaluationRecords = await EvaluationRecord.findAll({
        where: { user_id: userId },
        attributes: ['score']
      });

      const gameRecords = await GameRecord.findAll({
        where: { user_id: userId },
        attributes: ['score']
      });

      const dailyRecords = await DailyRecord.findAll({
        where: { user_id: userId },
        attributes: ['score']
      });

      const allScores = [
        ...evaluationRecords.map(r => r.score),
        ...gameRecords.map(r => r.score),
        ...dailyRecords.map(r => r.score)
      ];

      const averageScore = allScores.length > 0 ? 
        Math.round(allScores.reduce((sum, score) => sum + score, 0) / allScores.length * 10) / 10 : 0;

      return {
        totalPractices: evaluationCount + gameCount + dailyCount,
        evaluationCount,
        gameCount,
        dailyCount,
        averageScore,
        bestScore: allScores.length > 0 ? Math.max(...allScores) : 0
      };
    } catch (error) {
      throw new Error(`获取用户统计失败: ${error.message}`);
    }
  }

  // 获取最近的评测记录
  async getRecentEvaluations(userId, limit = 5) {
    try {
      return await EvaluationRecord.findAll({
        where: { user_id: userId },
        order: [['created_at', 'DESC']],
        limit
      });
    } catch (error) {
      throw new Error(`获取最近评测记录失败: ${error.message}`);
    }
  }

  // 获取最近的游戏记录
  async getRecentGames(userId, limit = 5) {
    try {
      return await GameRecord.findAll({
        where: { user_id: userId },
        order: [['created_at', 'DESC']],
        limit
      });
    } catch (error) {
      throw new Error(`获取最近游戏记录失败: ${error.message}`);
    }
  }

  // 获取连续签到天数
  async getContinuousDays(userId) {
    try {
      const records = await DailyRecord.findAll({
        where: { user_id: userId },
        order: [['date', 'DESC']],
        limit: 30 // 最多查询30天
      });

      if (records.length === 0) return 0;

      let continuousDays = 0;
      const today = new Date().toISOString().split('T')[0];
      
      for (let i = 0; i < records.length; i++) {
        const recordDate = records[i].date;
        const expectedDate = new Date();
        expectedDate.setDate(expectedDate.getDate() - i);
        const expectedDateStr = expectedDate.toISOString().split('T')[0];
        
        if (recordDate === expectedDateStr) {
          continuousDays++;
        } else {
          break;
        }
      }

      return continuousDays;
    } catch (error) {
      throw new Error(`获取连续天数失败: ${error.message}`);
    }
  }

  // 删除评测记录
  async deleteEvaluationRecord(id) {
    try {
      const affectedRows = await EvaluationRecord.destroy({
        where: { id }
      });
      if (affectedRows === 0) {
        throw new Error('评测记录不存在');
      }
      return true;
    } catch (error) {
      throw new Error(`删除评测记录失败: ${error.message}`);
    }
  }

  // 删除游戏记录
  async deleteGameRecord(id) {
    try {
      const affectedRows = await GameRecord.destroy({
        where: { id }
      });
      if (affectedRows === 0) {
        throw new Error('游戏记录不存在');
      }
      return true;
    } catch (error) {
      throw new Error(`删除游戏记录失败: ${error.message}`);
    }
  }

  // 删除每日记录
  async deleteDailyRecord(id) {
    try {
      const affectedRows = await DailyRecord.destroy({
        where: { id }
      });
      if (affectedRows === 0) {
        throw new Error('每日记录不存在');
      }
      return true;
    } catch (error) {
      throw new Error(`删除每日记录失败: ${error.message}`);
    }
  }
}

module.exports = new EvaluationDao();
